<?php
namespace backend\controllers;

use Yii;
use backend\models\SysCity;
use yii\web\AdminController;
use yii\web\NotFoundHttpException;

/**
 * Site controller
 */
class SiteController extends AdminController
{
    //public $layout=false;
    /**
     * @inheritdoc
     */

    public function init(){

    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        //取得左边菜单数据
        $this->getMenu();

        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
            //读取角色名称
            $roleNames = \common\helps\tools::getUserRoleName( $userInfo->userId);
        }else{
            $userName = '';
            $roleNames= '';
        }

        //此处向模板文件传变量数据
        $view = Yii::$app->view;
        $view->params['username'] = $userName;
        $view->params['roleName'] = $roleNames;                             //角色名称
        $view->params['verInfo'] = Yii::$app->params['verInfo'];
        $view->params['menuTitle'] = Yii::$app->params['menuTitle'];
        $view->params['verNumber'] = Yii::$app->params['verNumber'];

        return $this->render('index');
    }

    /**
     * @return string
     * 加载后台首页
     */
    public function actionHome()
    {
        $this->layout=false;
        return $this->render('home');
    }

    //错误页面
    public function actionError()
    {
        $exception = new NotFoundHttpException();
        if ($exception !== null) {
            return $this->render('error', ['statusCode' => $exception->statusCode,'exception'=>$exception->getName()]);
        }
    }

    /**
     * 强制刷新数据
     */
    public function actionRefreshData(){
        $sys_city = SysCity::find()->asArray()->all();
        $level = $level1 = $level2 = [];
        if (is_array($sys_city) && count($sys_city) > 0)foreach ($sys_city as $val){
            if ($val['level'] == 2)
                $level2[$val['id']] = $val;
            elseif ($val['level'] == 1)
                $level1[$val['id']] = $val;
            else 
                $level[$val['id']] = $val;
        }

        if (is_array($level2) && count($level2) > 0)foreach ($level2 as $val2){
            $level1[$val2['parent_id']]['son_val'][] = $val2;
        }
        if (is_array($level1) && count($level1) > 0)foreach ($level1 as $val1){
            $level[$val1['parent_id']]['son_val'][] = $val1;
        }

        $filename = dirname(dirname(__FILE__)).'/config/sys_city.php';
        $data = json_encode(array_values($level),JSON_UNESCAPED_UNICODE);
        file_put_contents($filename, $data);

    }
}
